package com.example.demo.study.thread.volatileTry;

/**
 * 分析volatile是否能保证原子性
 * 最经典的案例是i++
 */
public class VolatileAtomicTry {
    public volatile int race = 0;
    public  void increase() {
        race++;
    }
    public static void main(String[] args) throws InterruptedException {
        final VolatileAtomicTry test = new VolatileAtomicTry();
        Thread[] threads = new Thread[5]; // 存储线程引用

        for(int i=0;i<5;i++){
            threads[i] = new Thread(){
                public void run() {
                    for(int j=0;j<100000;j++)
                        test.increase();
                };
            };
            threads[i].start();
        }
        // 等待所有子线程结束（关键修复）
        for(Thread t : threads) {
            t.join(); // 主线程等待该子线程执行完毕
        }
        System.out.println(test.race);
    }
}
